package com.jms.fu.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.jms.fu.common.UIMessage;
import com.jms.fu.exception.DAOException;
import com.jms.fu.form.LoginForm;
import com.jms.fu.model.bean.User;
import com.jms.fu.model.bo.UserBO;
import com.jms.fu.vaidator.TextFieldValidator;

public class LoginMobileAction extends Action {
	private static Logger logger = Logger.getLogger(LoginAction.class);

	/**
	 * Method execute, called when executing the action
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		LoginForm loginForm = (LoginForm) form;
		HttpSession session = request.getSession();
		UserBO userBO = new UserBO();
		TextFieldValidator txtValid = new TextFieldValidator();
		try {
			if (txtValid.validate(loginForm.getUsername())
					&& txtValid.validate(loginForm.getPassword())) {
				int role = userBO.checkLogin(loginForm.getUsername()
						.toLowerCase(), loginForm.getPassword());
				if (role != -1) {
					if (userBO.checkStatus(loginForm.getUsername()) == 1) {
						request.setAttribute("ErrorInfo",
								UIMessage.BLOCKED_ACCOUNT);
						return mapping.findForward("failed");
					}
					session.setAttribute("username", loginForm.getUsername()
							.toLowerCase()); // gan username vao session
					
					if (role == 0) {
						session.setAttribute("role", "Administrator");
					} else if (role == 1) {
						session.setAttribute("role", "Developer");
					} else if (role == 2) {
						session.setAttribute("role", "Member");
					}
					User userInfo = new User();
					userInfo=userBO.getUserInfoByUsername(loginForm.getUsername());
					session.setAttribute("userInfo", userInfo);

					logger.info("Account logged: " + loginForm.getUsername());
					return mapping.findForward("success");

				} else {
					request.setAttribute("ErrorInfo", UIMessage.INVALID_LOGIN_ERROR);
					return mapping.findForward("failed");
				}
			} else {
				request.setAttribute("ErrorInfo", UIMessage.NULL_LOGIN_INFO);
				return mapping.findForward("failed");
			}
		} catch (DAOException e) {
			logger.error(e.getMessage());
			return mapping.findForward("failed");
		} catch (Exception e) {
			logger.error(e.getMessage());
			return mapping.findForward("failed");
		}
	}
}
